package com.schoolhelper.controller.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.longsh.optionframelibrary.OptionMaterialDialog;
import com.schoolhelper.model.Model;
import com.schoolhelper.model.MyRedissonManager;
import com.schoolhelper.model.dao.jsonparse.LwlControllerJsonParser;
import com.schoolhelper.model.dao.jsonparse.LwlJsonParser;
import com.schoolhelper.model.dao.okhttp.LwlRequestUrl;
import com.schoolhelper.model.dao.okhttp.RefactorRequestUrl;
import com.schoolhelper.model.entity.Order;
import com.schoolhelper.model.entity.OrderImage;
import com.schoolhelper.utils.ImageUtils;
import com.longsh.optionframelibrary.OptionBottomDialog;
import com.schoolhelper.utils.MyCache;
import com.schoolhelper.utils.constant.Api;
import com.schoolhelper.utils.constant.LwlApi;
import com.schoolhelper.utils.constant.MessageConstant;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PostActivity extends AppCompatActivity {
    private EditText postEtTitle;
    private EditText postEtDescription;
    private EditText postEtMoney;

    private Button postBtnSubmit;
    private ImageButton postBtnSub;
    private ImageButton postBtnAdd;
    private ImageButton postBtnBack2main;

    private Spinner postSpinnerCategory;
    private String category;

    private ImageView postIvDescription1;
    private ImageView postIvDescription2;
    private ImageView postIvDescription;

    private int imageWidth;
    private int imageHeight;

    private int imageId = 0;

    private List<String> getImageMethod = new ArrayList<String>();

    //拍照功能参数
    private static final int TAKE_PHOTO = 1;
    private static final int CHOOSE_PHOTO = 2;
    private final static int CROP_IMAGE = 3;
    //imageUri照片真实路径
    private Uri imageUri;
    //照片存储
    private File filePath;
    private File image1 = null;
    private File image2 = null;
    private File image3 = null;

    private static final int TAKE_PHOTO_PERMISSION_REQUEST_CODE = 1; // 拍照的权限处理返回码
    private static final int WRITE_SDCARD_PERMISSION_REQUEST_CODE = 1; // 写储存卡内容的权限处理返回码
    private static final int READ_SDCARD_PERMISSION_REQUEST_CODE = 1; // 读储存卡内容的权限处理返回码

    private LwlJsonParser lwlJsonParser;

    private int userId;
    RedissonClient redisson;
    volatile RLock lock;
    private String lockName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);

        initData();

        initListener();

        getPermission();
    }

    private void getPermission() {
        if (ContextCompat.checkSelfPermission(PostActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请写内存卡内容的权限
            ActivityCompat.requestPermissions(PostActivity.this,
                    new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_SDCARD_PERMISSION_REQUEST_CODE);
        }
        if (ContextCompat.checkSelfPermission(PostActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请读内存卡内容的权限
            ActivityCompat.requestPermissions(PostActivity.this,
                    new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, READ_SDCARD_PERMISSION_REQUEST_CODE);
        }
        if (ContextCompat.checkSelfPermission(PostActivity.this, android.Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            /*
             * 下面是对调用相机拍照权限进行申请
             */
            ActivityCompat.requestPermissions(PostActivity.this,
                    new String[]{android.Manifest.permission.CAMERA,}, TAKE_PHOTO_PERMISSION_REQUEST_CODE);
        }
    }

    private void initListener() {
        postBtnAdd.setOnClickListener(v -> addMoney());

        postBtnSub.setOnClickListener(v -> subMoney());

        postBtnSubmit.setOnClickListener(v -> submit());

        postIvDescription1.setOnClickListener(v -> {
            imageId = 1;
            selectImage();
        });

        postIvDescription2.setOnClickListener(v -> {
            imageId = 2;
            selectImage();
        });

        postIvDescription.setOnClickListener(v -> {
            imageWidth = postIvDescription.getWidth();
            imageHeight = postIvDescription.getHeight();
            System.out.println("宽高：\n" + imageWidth);
            System.out.println(imageHeight);

            if (postIvDescription1.getDrawable() == null) {
                imageId = 1;
                selectImage();
            } else if (postIvDescription2.getDrawable() == null) {
                imageId = 2;
                selectImage();
            } else {
                imageId = 3;
                selectImage();
            }
        });

        postSpinnerCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] categories = getResources().getStringArray(R.array.order_categories);
                category = categories[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        postBtnBack2main.setOnClickListener(v -> {
            postBack2main();
        });
    }

    private void postBack2main() {
        finish();
    }

    /**
     * 提交order
     */
    private void submit() {

        if (check()) {
            final OptionMaterialDialog optionMaterialDialog = new OptionMaterialDialog(PostActivity.this);
            optionMaterialDialog.setTitle("提交")
                    .setMessage("确认提交")
                    .setPositiveButton("确定", v -> {
                        optionMaterialDialog.dismiss();
                        lock.lock();
                            boolean postOrderResult = postOrder();
                            long orderId = getLastOrder().getOrderId();
                            boolean postImageResult = postAllImage(orderId);
                        lock.unlock();
                        if (postOrderResult && postImageResult) {
                            Toast.makeText(PostActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                            postBack2main();
                        } else {
                            System.out.println("上传order的结果：" + postOrderResult);
                            System.out.println("orderId：" + orderId);
                            System.out.println("上传图片的结果：" + postImageResult);
                            Toast.makeText(PostActivity.this, "发布失败", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .setNegativeButton("取消", v -> optionMaterialDialog.dismiss())
                    .setCanceledOnTouchOutside(true)
                    .show();
        }
    }

    private Order getLastOrder() {
        Map<String, String> headers = new HashMap<>();
        Order lastOrder = RefactorRequestUrl.postThenGetOne(Api.BASE_URL, LwlApi.GET_LAST_ORDER, headers, null, Order.class, lwlJsonParser);
        System.out.println("lastOrder：" + lastOrder.toString());
        return lastOrder;
    }

    private boolean postAllImage(long orderId) {
        try {
            Model.getInstance().getGlobalSingleThreadPool().execute(() -> {
                if (image1 != null) {
                    String image1Url = postImageToSmms(image1);
                    if (image1Url.equals(MessageConstant.FAIL_MSG)) {
                        throw new Error();
                    }
                    if (!postImageToOrderImage(orderId, image1Url)) {
                        throw new Error();
                    }
                    System.out.println("图片上传成功");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        try {
            Model.getInstance().getGlobalSingleThreadPool().execute(() -> {
                if (image2 != null) {
                    String image2Url = postImageToSmms(image2);
                    if (image2Url.equals(MessageConstant.FAIL_MSG)) {
                        throw new Error();
                    }
                    if (!postImageToOrderImage(orderId, image2Url)) {
                        throw new Error();
                    }
                    System.out.println("图片上传成功");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        try {
            Model.getInstance().getGlobalSingleThreadPool().execute(() -> {
                if (image3 != null) {
                    String image3Url = postImageToSmms(image3);
                    if (image3Url.equals(MessageConstant.FAIL_MSG)) {
                        throw new Error();
                    }
                    if (!postImageToOrderImage(orderId, image3Url)) {
                        throw new Error();
                    }
                    System.out.println("图片上传成功");
                }
            });
        } catch (Error | Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    private boolean postImageToOrderImage(long orderId, String imageUrl) {
        Map<String, String> headers = new HashMap<>();
        OrderImage orderImage = new OrderImage(null, orderId, imageUrl);
        return LwlRequestUrl.justPost(Api.BASE_URL, Api.ORDER_IMAGE, headers, orderImage, lwlJsonParser);
    }

    /**
     * 把图像上传到图床，参数是File类对象，返回结果是图像的url
     * @param image
     * @return
     */
    private String postImageToSmms(File image) {
        Map<String, String> headers = new HashMap<>();
        headers.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36");
        headers.put("Authorization", "mc1bMY0iL1hW9N478FWQ0AZ3B11TqBw9");
        return LwlRequestUrl.postSmmsThenGetUrl(LwlApi.BSER_SMMSURL, LwlApi.SMMS_UPLOAD, headers, image, lwlJsonParser);
    }

    private boolean postOrder() {
        Order order = new Order(null,
                userId,
                postEtTitle.getText().toString(),
                category,
                postEtDescription.getText().toString(),
                Integer.parseInt(postEtMoney.getText().toString()),
                "0",
                null,
                new Date(),
                null,
                null);

        boolean postOrderResult = RefactorRequestUrl.justPost(Api.BASE_URL, Api.ORDER, new HashMap<>(), order, lwlJsonParser);
        if (postOrderResult) {
            return true;
        } else {
            Toast.makeText(PostActivity.this, "发布失败", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    private boolean check() {
        if (Integer.parseInt(postEtMoney.getText().toString()) < 1) {
            Toast.makeText(PostActivity.this, "跑腿费至少是1元及以上哦", Toast.LENGTH_SHORT).show();
            return false;
        } else if (postEtTitle.getText().toString().equals("")) {
            Toast.makeText(PostActivity.this, "标题不能为空", Toast.LENGTH_SHORT).show();
            return false;
        } else if (postEtDescription.getText().toString().equals("")) {
            Toast.makeText(PostActivity.this, "介绍不能为空", Toast.LENGTH_SHORT).show();
            return false;
        } else if (category.equals("无")) {
            Toast.makeText(PostActivity.this, "分类不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     *
     * 获取图片，即可拍照，也可以本地上传
     *
     */
    private void selectImage() {
        final OptionBottomDialog optionBottomDialog = new OptionBottomDialog(PostActivity.this, getImageMethod);
        optionBottomDialog.setItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // optionBottomDialog.dismiss();
                switch (position) {
                    case 0:
                        //启动相机程序
                        //隐式Intent
                        Intent intent_photo = new Intent("android.media.action.IMAGE_CAPTURE");
                        //putExtra()指定图片的输出地址，填入之前获得的Uri对象
                        imageUri = ImageUtils.getImageUri(PostActivity.this);
                        intent_photo.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        //startActivity( intent_photo );
                        startActivityForResult(intent_photo, TAKE_PHOTO);
                        //底部弹框消失
                        optionBottomDialog.dismiss();
                        break;
                    case 1:
                        //打开相册
                        openAlbum();
                        //底部弹框消失
                        optionBottomDialog.dismiss();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    //打开相册
    private void openAlbum() {
        Intent intent_album = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(intent_album, CHOOSE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    //需要对拍摄的照片进行处理编辑
                    //拍照成功的话，就调用BitmapFactory的decodeStream()方法把图片解析成Bitmap对象，然后显示
                    Log.i("Test", "onActivityResult TakePhoto : " + imageUri);
                    //Bitmap bitmap = BitmapFactory.decodeStream( getContentResolver().openInputStream( imageUri ) );
                    //takephoto.setImageBitmap( bitmap );
                    //设置照片存储文件及剪切图片
                    File saveFile = ImageUtils.getTempFile();
                    filePath = ImageUtils.getTempFile();
                    startImageCrop(saveFile, imageUri);
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    //选中相册照片显示
                    Log.i("Test", "onActivityResult: 执行到打开相册了");
                    try {
                        imageUri = data.getData(); //获取系统返回的照片的Uri
                        Log.i("Test", "onActivityResult: uriImage is " + imageUri);
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getContentResolver().query(imageUri,
                                filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        String path = cursor.getString(columnIndex);  //获取照片路径
                        cursor.close();
                        Bitmap bitmap = BitmapFactory.decodeFile(path);
                        //                        photo_taken.setImageBitmap(bitmap);
                        //设置照片存储文件及剪切图片
                        File saveFile = ImageUtils.setTempFile(PostActivity.this);
                        filePath = ImageUtils.getTempFile();
                        startImageCrop(saveFile, imageUri);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CROP_IMAGE:
                if (resultCode == RESULT_OK) {
                    Log.i("Test", "onActivityResult: CROP_IMAGE" + "进入了CROP");
                    // 通过图片URI拿到剪切图片
                    //bitmap = BitmapFactory.decodeStream( getContentResolver().openInputStream( imageUri ) );
                    //通过FileName拿到图片
                    Bitmap bitmap = BitmapFactory.decodeFile(filePath.toString());
                    //把裁剪后的图片展示出来
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) postIvDescription.getLayoutParams();
                    params.height = imageHeight;
                    params.width = imageWidth;
                    params.setMargins(20, 30, 0, 0);
                    if (imageId == 1) {
                        System.out.println("填充第一个图片");
                        postIvDescription1.setLayoutParams(params);
                        postIvDescription1.setImageBitmap(bitmap);
                        image1 = filePath;
                    } else if (imageId == 2) {
                        System.out.println("填充第二个图片");
                        postIvDescription2.setLayoutParams(params);
                        postIvDescription2.setImageBitmap(bitmap);
                        image2 = filePath;
                    } else if (imageId == 3) {
                        System.out.println("填充第三个图片");
                        postIvDescription.setImageBitmap(bitmap);
                        image3 = filePath;
                    }
//                    postIvDescription.setImageBitmap( bitmap );
                    //ImageUtils.Compress( bitmap );
                }
                break;
            default:
                break;
        }
    }

    //剪切图片
    private void startImageCrop(File saveToFile, Uri uri) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        Log.i("Test", "startImageCrop: " + "执行到压缩图片了" + "uri is " + uri);
        intent.setDataAndType(uri, "image/*");//设置Uri及类型
        //uri权限，如果不加的话，   会产生无法加载图片的问题
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.putExtra("crop", "true");//
        intent.putExtra("aspectX", 1);//X方向上的比例
        intent.putExtra("aspectY", 1);//Y方向上的比例
        intent.putExtra("outputX", imageHeight);//裁剪区的X方向宽
        intent.putExtra("outputY", imageWidth);//裁剪区的Y方向宽
        intent.putExtra("scale", true);//是否保留比例
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        intent.putExtra("return-data", false);//是否将数据保留在Bitmap中返回dataParcelable相应的Bitmap数据，防止造成OOM，置位false

        //判断文件是否存在
        //File saveToFile = ImageUtils.getTempFile();
        if (!saveToFile.getParentFile().exists()) {
            saveToFile.getParentFile().mkdirs();
        }
        //将剪切后的图片存储到此文件
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(saveToFile));
        Log.i("Test", "startImageCrop: " + "即将跳到剪切图片");
        startActivityForResult(intent, CROP_IMAGE);
    }

    /**
     * 获取图片代码结束
     */

    private void subMoney() {
        int money = Integer.parseInt(String.valueOf(postEtMoney.getText()));
        if (money > 1) {
            postEtMoney.setText(money - 1 + "");
        }
    }

    private void addMoney() {
        postEtMoney.setText(Integer.parseInt(String.valueOf(postEtMoney.getText())) + 1 + "");
    }

    private void initData() {
        postEtTitle = findViewById(R.id.post_et_title);
        postEtDescription = findViewById(R.id.post_et_description);

        postEtMoney = findViewById(R.id.post_et_money);

        postBtnSubmit = findViewById(R.id.post_btn_submit);
        postBtnSub = findViewById(R.id.post_btn_sub);
        postBtnAdd = findViewById(R.id.post_btn_add);
        postBtnBack2main = findViewById(R.id.post_btn_back2main);

        postSpinnerCategory = findViewById(R.id.post_spinner_category);

        postIvDescription = findViewById(R.id.post_iv_description);
        postIvDescription1 = findViewById(R.id.post_iv_description_1);
        postIvDescription2 = findViewById(R.id.post_iv_description_2);

        getImageMethod.add("拍照");
        getImageMethod.add("从相册选择");

        lwlJsonParser = new LwlControllerJsonParser();

        userId = Integer.parseInt(MyCache.read(getApplicationContext(), "userId"));

        lockName = "postOrderThenPostImage2";
        synchronized (this) {
            // 连接redis
            new Thread(() -> {
                redisson = MyRedissonManager.getRedisson();
                // 获取锁
                lock = redisson.getLock(lockName);
            }).start();
        }
    }
}